<template>
  <view class="message-container">
    <!-- 顶部栏 -->
    <view class="top-bar">
      <u-tabs :list="tabs" :current="tabIndex" @change="tabChange" class="custom-tabs" :active-color="'#57C8F2'"
        :inactive-color="'#666'" />
      <u-icon name="more-dot-fill" size="28" color="#fff" class="more-btn" />
    </view>
    <!-- 横幅提示 -->
    <view class="banner">
      <text>关注{{ globalConfig.name }}开启消息提示功能，不错过缘分~</text>
      <u-button type="primary" size="mini" shape="circle" class="follow-btn">去关注</u-button>
    </view>
    <!-- 聊天类型切换 -->
    <view v-if="tabIndex === 0" class="chat-type-tabs">
      <u-tabs :list="chatTypeList" :current="chatTypeIndex" @change="chatTypeChange" :active-color="'#57C8F2'"
        :inactive-color="'#666'" class="type-tabs" />
    </view>
    <!-- 聊天列表 -->
    <view v-if="tabIndex === 0" class="content-section">
      <view v-for="(item, index) in chatList" :key="index" class="chat-item" @click="goToChatDetail(item)">
        <u-avatar :src="globalConfig.site_url + item.opposite_user.image" size="64" v-if="chatTypeIndex == 0" />
        <u-avatar :src="globalConfig.site_url + item.user_info.image" size="64" v-if="chatTypeIndex == 1" />
        <view class="chat-info">
          <view class="chat-header">
            <text class="nickname" v-if="chatTypeIndex == 0">{{ item.opposite_user.nickname }}</text>
            <text class="nickname" v-if="chatTypeIndex == 1">{{ item.title }}</text>
            <text class="time" v-if="item.last_message">{{ formatTime(item.last_message.createtime) }}</text>
          </view>
          <text class="last-msg" >{{ item.last_message.info }}</text> 
        </view>
        <view class="chat-badge" v-if="item.unread_count > 0">{{ item.unread_count }}</view>
      </view>
      <u-empty v-if="chatList.length === 0" text="暂无聊天记录" mode="message" />
    </view>
    <!-- 关于我列表 -->
    <view v-else class="content-section">
      <view class="about-item" @click="goToFans">
        <u-icon name="heart" size="36" color="#ff4d4f" class="about-icon" />
        <text class="about-text">新增粉丝</text>
        <u-icon name="arrow-right" size="28" color="#888" />
      </view>
      <view class="about-item" @click="goToLikes">
        <u-icon name="thumb-up" size="36" color="#faad14" class="about-icon" />
        <text class="about-text">点赞与评论</text>
        <u-icon name="arrow-right" size="28" color="#888" />
      </view>
    </view>
    	<!-- uView登录弹窗 (from shop-list.vue) -->
		<u-popup v-model="showLoginPopup" mode="center" border-radius="16" width="600rpx" :mask-close-able="true"
			@close="closeLoginPopup">
			<view class="login-popup">
				<view class="popup-header">
					<view class="popup-title">登录</view>
					<view class="popup-close" @click="closeLoginPopup">
						<u-icon name="close" color="#999" size="20"></u-icon>
					</view>
				</view>

				<view class="login-methods">
					<u-button type="success" shape="round" :loading="wechatLoading" @click="handleWechatLogin"
						:custom-style="{ backgroundColor: '#07c160', borderColor: '#07c160', marginBottom: '20rpx' }">
						<u-icon name="weixin-fill" color="#fff" size="20" style="margin-right: 10rpx"></u-icon>
						{{ wechatLoading ? '登录中...' : '微信登录' }}
					</u-button>
				</view>

				<view class="login-tips">
					<u-checkbox v-model="agreePolicy" shape="circle" active-color="#57C8F2" :size="32"
						style="margin-right: 10rpx;" />
					<text class="tips-text">我已阅读并同意</text>
					<text class="link-text" @click="showPrivacy('agreement')">《用户协议》</text>
					<text class="tips-text">和</text>
					<text class="link-text" @click="showPrivacy('policy')">《隐私政策》</text>
				</view>
			</view>
		</u-popup>
  </view>
</template>

<script>
import { getChatList } from '@/api/user.js'
import { mapGetters, mapState } from 'vuex';
import {
	checkLoginStatus,
	wechatMiniLogin
} from '@/common/auth.js';

export default {
  name: 'MessageIndex',
  data() {
    return {
      showLoginPopup: false,
			agreePolicy: false,
			wechatLoading: false,
      tabs: [
        { name: '聊天' },
        // { name: '关于我' }
      ],
      tabIndex: 0,
      chatTypeList: [
        { name: '私聊' },
        { name: '群组' }
      ],
      chatTypeIndex: 0,
      chatList: [],
      groupList: []
    }
  },
  onLoad() {
    this.getChatData()
  },
  onShow() {
    this.getMessageList && this.getMessageList();
    uni.$on('refreshMessageIndex', () => {
      this.getMessageList && this.getMessageList();
    });
  },
  onUnload() {
    uni.$off('refreshMessageIndex');
  },
  mounted() {
    this.getChatData()
  },
  computed: {
    ...mapGetters(['getUserInfo']),
    ...mapState({
      globalConfig: state => state.config,
      userLocation: state => state.location,
      userInfo: state => state.userInfo,
    })
  },
  methods: {
    formatTime(timestamp) {
      if (!timestamp) return '';
      // 兼容后端返回字符串或数字
      let ts = Number(timestamp);
      if (isNaN(ts) || ts <= 0) return '';
      // 秒级时间戳自动转为毫秒
      if (ts < 10000000000) ts = ts * 1000;
      const date = new Date(ts);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },
    tabChange(index) {
      this.tabIndex = index;
    },
    chatTypeChange(index) {
      this.chatTypeIndex = index;
      this.getChatData();
    },
    async getChatData() {
        const isLoggedIn = await checkLoginStatus();
				if (!isLoggedIn) {
					this.showLoginPopup = true;
					return;
				}
      try {
        const res = await getChatList({
          type: this.chatTypeIndex === 0 ? 2 : 1,

        })
        if (res.data && res.data.code === 1) {
          this.chatList = res.data.data || []
        }
      } catch (error) {
        console.error('获取聊天列表失败:', error)
        uni.showToast({ title: '获取聊天列表失败', icon: 'none' })
      }
    },
    goToChatDetail(item) {
      if (this.chatTypeIndex === 0) {
        uni.navigateTo({ url: `/pages/chat/detail?teamId=${item.id}` })
      } else if (this.chatTypeIndex === 1) {
        // 群组聊天
        this.goToGroupChat(item)
      }
    },
    goToGroupChat(item) {
      console.log(item);
      uni.navigateTo({
        url: `/pages/chat/detail?teamId=${item.id}&isTeamChat=true&userId=${this.userInfo.id}&nickName=${this.userInfo.nickName}&teamInfo=${JSON.stringify(item)}`
      })
    },
    goToFans() {
      uni.navigateTo({ url: `/pages/me/fans` })
    },
    goToLikes() {
      uni.navigateTo({ url: `/pages/me/interactions` })
    },
     async handleWechatLogin() {
      // 判断有没有勾选隐私
      if (!this.agreePolicy) {
        this.$u.toast('请先勾选同意《用户协议》和《隐私政策》');
        return;
      }
      if (this.wechatLoading) return;
      this.wechatLoading = true;
      try {
        const result = await wechatMiniLogin();
        if (result.success) {
          this.$store.dispatch('fetchUserInfoAction');
          this.closeLoginPopup();
          this.$u.toast('登录成功');
          this.getChatData();
        } else {
          throw new Error(result.message || '登录失败');
        }
      } catch (error) {
        this.$u.toast(error.message || '登录操作失败');
      } finally {
        this.wechatLoading = false;
      }
    },
    closeLoginPopup() {
      this.showLoginPopup = false;
      this.wechatLoading = false;
    },
  }
}
</script>

<style scoped>
.message-container {
  padding-top: 100rpx;
  min-height: 100vh;
  background: #1a1a1a;
}

.top-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  background: #1a1a1a;
}

.custom-tabs {
  flex: 1;
}

.more-btn {
  margin-left: 16rpx;
}

.banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #1a1a1a;
  color: #fff;
  border-radius: 12rpx;
  margin: 0 32rpx 16rpx 32rpx;
  padding: 16rpx 24rpx;
  font-size: 26rpx;
  border: 1px solid #333;
}

.chat-type-tabs {
  padding: 0 32rpx 16rpx;
}

.type-tabs {
  --u-tabs-height: 60rpx;
  --u-tabs-font-size: 28rpx;
}

.follow-btn {
  color: #fff !important;
}

.content-section {
  padding: 0 32rpx;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1px solid #333;
}

.chat-info {
  flex: 1;
  margin-left: 20rpx;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nickname {
  font-size: 30rpx;
  font-weight: 500;
  color: #fff;
}

.time {
  font-size: 22rpx;
  color: #aaa;
}

.last-msg {
  font-size: 26rpx;
  color: #aaa;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}

.about-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  background: #1a1a1a;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  border: 1px solid #333;
}

.about-icon {
  margin-right: 24rpx;
}

.about-text {
  font-size: 30rpx;
  flex: 1;
  color: #fff;
}

.u-empty__text {
  color: #aaa !important;
}

::v-deep .u-tabs {
  background-color: transparent;
}

::v-deep .u-tabs {
  background-color: #1a1a1a !important;
}
</style>
